﻿Imports System.Data.SqlClient
Imports DevExpress.XtraReports.UI

Public Class frmAsignarTarjeta
    Dim existe As Boolean
    Public RnpPaciente As String
    Dim IdTipoPaciente As Integer
    Private Sub frmAsignarTarjeta_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: esta línea de código carga datos en la tabla 'LabCDMDataSet.Paciente' Puede moverla o quitarla según sea necesario.
        Me.PacienteTableAdapter.Fill(Me.LabCDMDataSet.Paciente)
        If RnpPaciente <> Nothing Then
            Me.cboPaciente.EditValue = RnpPaciente
        End If
    End Sub

    Private Async Sub cboPaciente_EditValueChanged(sender As Object, e As EventArgs) Handles cboPaciente.EditValueChanged
        Try
            If varConexion.State = ConnectionState.Open Then
                varConexion.Close()
            End If

            Await varConexion.OpenAsync()

            Dim sqlCargarDatos As String = String.Format("SELECT a.Rnp_Paciente, a.Nombres, a.Apellidos, a.Fecha_Nacimiento, b.Sexo, a.Telefono, c.Tipo_Paciente, a.Id_Tipo_Paciente FROM Paciente a INNER JOIN Sexo b ON a.Id_Sexo = b.Id_Sexo INNER JOIN Tipo_Paciente c ON a.Id_Tipo_Paciente = c.Id_Tipo_Paciente WHERE Rnp_Paciente = '{0}'", Me.cboPaciente.EditValue)

            Dim cmd As New SqlCommand(sqlCargarDatos, varConexion)
            Dim reader As SqlDataReader = Await cmd.ExecuteReaderAsync()

            If Await reader.ReadAsync() Then
                Me.txtNombres.EditValue = reader.Item("Nombres")
                Me.txtApellidos.EditValue = reader.Item("Apellidos")
                Me.txtEdad.EditValue = CInt(DateDiff(DateInterval.Month, CDate(reader.Item("Fecha_Nacimiento")), Date.Today.Date) / 12)
                Me.txtSexo.EditValue = reader.Item("Sexo")
                Me.txtTelefono.EditValue = reader.Item("Telefono")
                Me.txtTipoPaciente.EditValue = reader.Item("Tipo_Paciente")
                IdTipoPaciente = CInt(reader.Item("Id_Tipo_Paciente"))
            Else
                MessageBox.Show("No se ha encontrado este paciente.", varTitulo, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

            varConexion.Close()

            ObtenerNumTarjetaActual()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub ObtenerNumTarjetaActual()
        Try
            If varConexion.State = ConnectionState.Open Then
                varConexion.Close()
            End If

            varConexion.Open()

            Dim sql As String = String.Format("SELECT Codigo_Membresia, Rnp_Paciente, Fecha_Membresia FROM Membresia WHERE Rnp_Paciente = '{0}'", Me.cboPaciente.EditValue)
            Dim cmd As New SqlCommand(sql, varConexion)
            Dim reader As SqlDataReader = cmd.ExecuteReader()

            If reader.Read() Then
                If IsDBNull(reader.Item("Codigo_Membresia")) Then
                    Me.txtCodigoMembresia.EditValue = Nothing
                    existe = False
                Else
                    Me.txtCodigoMembresia.EditValue = reader.Item("Codigo_Membresia")
                    existe = True
                End If
            Else
                Me.txtCodigoMembresia.EditValue = Nothing
                existe = False
            End If

            varConexion.Close()

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub btnGuardar_Click(sender As Object, e As EventArgs) Handles btnGuardar.Click
        If existe = False Then
            'insertamos el nuevo
            Me.MembresiaTableAdapter1.Insert(Me.txtCodigoMembresia.EditValue, Me.cboPaciente.EditValue, Date.Today.Date)
        Else
            'actualizamos
            ActualizarMembresia()
        End If
        MessageBox.Show("Se ha guardado la membresía.", varTitulo, MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Private Sub btnCerrar_Click(sender As Object, e As EventArgs) Handles btnCerrar.Click
        Me.Dispose()
        Me.Close()
    End Sub

    Private Sub ActualizarMembresia()
        Try
            If varConexion.State = ConnectionState.Open Then
                varConexion.Close()
            End If

            varConexion.Open()

            Dim sql As String = String.Format("UPDATE Membresia SET Codigo_Membresia = '{0}' WHERE Rnp_Paciente = '{1}'", Me.txtCodigoMembresia.EditValue, Me.cboPaciente.EditValue)
            Dim cmd As New SqlCommand(sql, varConexion)

            cmd.ExecuteNonQuery()

            varConexion.Close()

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub btnImprimirCarnet_Click(sender As Object, e As EventArgs) Handles btnImprimirCarnet.Click
        If IdTipoPaciente = 1 Then
            'Frecuente
            Dim rptImprime As New rptCarnetClienteFrecuente
            'Dim rptImprime As New rptCodigosBarras
            rptImprime.CargarDatosCarnet(CStr(Me.cboPaciente.EditValue))
            Dim reportTool As New ReportPrintTool(rptImprime)
            reportTool.Report.CreateDocument(False)
            reportTool.PrintingSystem.PageSettings.Landscape = True
            reportTool.PrintingSystem.PageSettings.PaperName = "CR80"
            reportTool.PrintingSystem.PageSettings.PaperKind = Printing.PaperKind.Custom
            reportTool.PrintingSystem.PageSettings.PrinterName = "Evolis Zenius"
            reportTool.ShowRibbonPreviewDialog()

        ElseIf IdTipoPaciente = 2 Then
            'Diabético
            Dim rptImprime As New rptCarnetPacienteDiabetico
            rptImprime.CargarDatosCarnet(CStr(Me.cboPaciente.EditValue))
            Dim reportTool As New ReportPrintTool(rptImprime)
            reportTool.Report.CreateDocument(False)
            reportTool.PrintingSystem.PageSettings.Landscape = True
            reportTool.PrintingSystem.PageSettings.PaperName = "CR80"
            reportTool.PrintingSystem.PageSettings.PaperKind = Printing.PaperKind.Custom
            reportTool.PrintingSystem.PageSettings.PrinterName = "Evolis Zenius"
            reportTool.ShowRibbonPreviewDialog()

        ElseIf IdTipoPaciente = 3 Then
            'Diálisis
            Dim rptImprime As New rptPacienteDialisis
            rptImprime.CargarDatosCarnet(CStr(Me.cboPaciente.EditValue))
            Dim reportTool As New ReportPrintTool(rptImprime)
            reportTool.Report.CreateDocument(False)
            reportTool.PrintingSystem.PageSettings.Landscape = True
            reportTool.PrintingSystem.PageSettings.PaperName = "CR80"
            reportTool.PrintingSystem.PageSettings.PaperKind = Printing.PaperKind.Custom
            reportTool.PrintingSystem.PageSettings.PrinterName = "Evolis Zenius"
            reportTool.ShowRibbonPreviewDialog()

        End If
    End Sub
End Class